/**
 * 
 */
package com.sinodata.bsm.cicp.collector.oracle;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.DBConnectionUtil;
import com.sinodata.bsm.common.constants.SeparatorConstants;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author wangxiao
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * Apr 17, 2013 9:51:06 AM          wangxiao        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class SQLExecutionTopNCollector extends AbstractJDBCCollector {
    private final Logger logger = Logger.getLogger(SQLExecutionTopNCollector.class);

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        String dbname = this.getParamMap().get("DBName");
        String dbtype = this.getParamMap().get("DBType");
        String sql = this.getParamMap().get("SQL");
        int topN = Integer.parseInt(this.getParamMap().get("TopN"));
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            conn = DBConnectionUtil.getInstance().getConnection(dbtype, ip, dbname);
            statement = conn.prepareStatement(sql);
            statement.setInt(1, topN);
            //	        ResultSet rs= this.getCachedResultSet(dbtype, ip, dbname, sql);
            ResultSet rs = statement.executeQuery();
            String result = dealResult(rs);
            ResPropertyValue propertyValueX = new ResPropertyValue();
            ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
            for (int i = 0; i < propMetas.length; i++) {
                propValues[i] = ResPropertyValue.createPropValue(result, propMetas[i]);
            }
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
            rs.close();
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                logger.error(e);
                e.printStackTrace();
            }
        }
        return values;
    }

    private String dealResult(ResultSet rs) throws SQLException {
        StringBuffer sb = new StringBuffer();
        while (rs.next()) {
            //TODO针对结果集进行处理
            sb.append(rs.getString("USERNAME"));
            sb.append(SeparatorConstants.COL_SEPARATOR);
            sb.append(rs.getString("CPU_TIME"));
            sb.append(SeparatorConstants.COL_SEPARATOR);
            sb.append(rs.getString("ELAPSED_TIME"));
            sb.append(SeparatorConstants.COL_SEPARATOR);
            sb.append(rs.getString("SQL_TEXT"));
            sb.append(SeparatorConstants.COL_SEPARATOR);
            sb.append(SeparatorConstants.LIN_SEPARATOR);
        }
        return sb.toString();
    }

    @Override
    public String[] getParamMeta() {
        //参数：数据库类型，数据库实例名，要使用的SQL，要查询的topN数
        return new String[] { "DBType", "DBName", "SQL", "TopN" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "$1" };
    }

}
